package src.scheduling;

import java.util.ArrayList;
import java.util.Random;

import src.adt.Process;
import src.adt.User;

public class Lottery {

	ArrayList<Process> allProcesses;
	ArrayList<User> allUsers;
	ArrayList<Process> schedule;
	public int clock;
	ArrayList<Process> addedProcesses;

	public Lottery(ArrayList<Process> allProcesses, ArrayList<User> allUsers) {

		this.allProcesses = allProcesses;
		this.allUsers = allUsers;
		clock = 0;
		schedule = new ArrayList<Process>();
		
		addedProcesses = new ArrayList<Process>();
		
		run();

	}

	public void run() {

		int totalRunTime = 0;
		for (Process process : allProcesses) {
			totalRunTime += process.runTime;
		}
		
		Random rand = new Random();
		int winningTicket = 0;

		while (clock < totalRunTime) {
			
			addArrivedProcesses(clock);
			winningTicket = rand.nextInt(schedule.size());
			System.out.println("the winnig Ticket is " + winningTicket);

			schedule.get(winningTicket).run(1);
			clock++;

			removeFinishedProcesses(winningTicket);

		}

	}
	
	public void printArray(ArrayList<Process> x){
		for(Process p: x )
			System.out.println(p.name);
	}

	public void removeFinishedProcesses(int luckyProcessIndex) {

		Process luckyProcess = schedule.get(luckyProcessIndex);
		if (luckyProcess.remainingTime == 0)
			for (int i = 0;i<schedule.size();i++)
				if (schedule.get(i).name.equals(luckyProcess.name)){
					
					System.out.println(schedule.get(i).name + " is removed.");
					schedule.remove(i);
					i--;
					
				}
		printArray(schedule);

	}

	public void addArrivedProcesses(int clock) {

		for (int i = 0; i < allProcesses.size(); i++) {
			Process runningProcess = allProcesses.get(i);
			if (runningProcess.arrivalTime <= clock
					&& !addedProcesses.contains(runningProcess)) {
				giveTickets(allProcesses.get(i));
				addedProcesses.add(allProcesses.get(i));
			}
		}
	}

	public void giveTickets(Process process) {

		for (int i = 0; i < getUserPriority(process); i++)
			schedule.add(process);

	}

	public int getUserPriority(Process process) {

		String userName = process.userName;

		for (User user : allUsers) {

			if (user.userName.equals(userName))
				return user.priority;

		}

		return -1;

	}

}
